import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:toys_flutter/components/AuthSpan.dart';
import 'package:toys_flutter/components/AgeSpan.dart';
import 'package:toys_flutter/components/LevelSpan.dart';
import 'package:toys_flutter/components/MyAvatarWidget.dart';
import 'package:toys_flutter/pages/UserDetail.dart';
import 'package:toys_flutter/utils/index.dart';

class DynamicItem extends StatefulWidget {
  final void Function() onTap;
  final Map<String, dynamic>? item;

  const DynamicItem({super.key, required this.onTap, required this.item});

  @override
  _DynamicItemState createState() => _DynamicItemState();
}

class _DynamicItemState extends State<DynamicItem> {
  @override
  Widget build(BuildContext context) {
    if (widget.item == null) {
      return const SizedBox.shrink(); // 返回一个空的占位符
    }

    return Container(
      padding: const EdgeInsets.all(5),
      margin: const EdgeInsets.all(5),
      child: Card(
        color: Colors.transparent, // 设置背景为透明
        elevation: 0, // 可选：设置阴影为 0
        child: Padding(
          padding: const EdgeInsets.all(5),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 用户信息
              _buildUserInfo(context, widget.item),
              // 动态详情和图片组合
              InkWell(
                onTap: widget.onTap,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildRichText(context, widget.item),
                    _buildImages(context, widget.item),
                  ],
                ),
              ),
              // 总数量
              _buildTotalCount(widget.item),
              // 动态操作
              _buildDynamicAction(),
            ],
          ),
        ),
      ),
    );
  }

  // 总数量
  Widget _buildTotalCount(Map<String, dynamic>? item) {
    if (item == null) {
      return const SizedBox.shrink(); // 返回一个空的占位符
    }

    final int imageCount = item['image_count'] ?? 0;
    final int createTime = item['create_time'] ?? 0;
    final String position;
    if (item.containsKey('position') &&
        item['position'].containsKey('position')) {
      position = item['position']['position'] ?? '保密';
    } else {
      position = '保密';
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 5),
        Text(
          '1/$imageCount',
          style: const TextStyle(fontSize: 12, color: Colors.black54),
        ),
        const SizedBox(height: 5),
        Text(
          DateTimeUtils.convertTimestampToDateString(createTime),
          style: const TextStyle(fontSize: 12, color: Colors.black54),
        ),
        const SizedBox(height: 5),
        Row(
          children: [
            const Icon(Icons.location_on, size: 15, color: Colors.black54),
            Text(
              position,
              style: const TextStyle(fontSize: 12, color: Colors.black54),
            ),
          ],
        ),
        const SizedBox(height: 10),
      ],
    );
  }

  // 操作按钮
  Widget _buildDynamicAction() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        // 点赞
        GestureDetector(
          onTap: () {
            print('点赞');
          },
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.thumb_up_outlined, size: 14, color: Colors.black54),
              SizedBox(width: 4), // 控制间距
              Text('点赞', style: TextStyle(fontSize: 12, color: Colors.black54)),
            ],
          ),
        ),
        const SizedBox(
          width: 20,
        ),
        // 评论
        GestureDetector(
          onTap: () {
            print('评论');
          },
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.comment_outlined, size: 14, color: Colors.black54),
              SizedBox(width: 4), // 控制间距
              Text('评论', style: TextStyle(fontSize: 12, color: Colors.black54)),
            ],
          ),
        ),
        const SizedBox(
          width: 20,
        ),
        // 打招呼
        GestureDetector(
          onTap: () {
            print('打招呼');
          },
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.chat_bubble_outline, size: 14, color: Colors.black54),
              SizedBox(width: 4), // 控制间距
              Text('打招呼',
                  style: TextStyle(fontSize: 12, color: Colors.black54)),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildImages(BuildContext context, Map<String, dynamic>? item) {
    if (item == null) {
      return const SizedBox.shrink(); // 返回一个空的占位符
    }
    final String image = item['image'];

    // 计算图片宽度
    final double imageWidth = (MediaQuery.of(context).size.width - 30) / 3;

    // 如果 image结尾是图片就展示图片，如果是视频就展示视频
    if (image.endsWith('.jpg') ||
        image.endsWith('.png') ||
        image.endsWith('.jpeg')) {
      return InkWell(
          onTap: () {
            TDImageViewer.showImageViewer(
              context: context,
              images: [image],
              defaultIndex: 0, // 传递点击的索引
            );
          },
          child: CachedNetworkImage(
            imageUrl: image,
            placeholder: (context, url) => const Center(
              child: SizedBox(
                width: 20.0,
                height: 20.0,
                child: CircularProgressIndicator(strokeWidth: 2.0),
              ),
            ),
            errorWidget: (context, url, error) => const Icon(Icons.error),
            width: imageWidth,
            height: imageWidth,
            fit: BoxFit.cover,
          ),
      );
    } else if (image.endsWith('.mp4')) {
      // 视频
      return SizedBox(
        width: imageWidth,
        height: imageWidth,
        // child: VideoWidget(videoUrl: image),
        child: const Text('视频'),
      );
    } else {
      return const SizedBox.shrink(); // 返回一个空的占位符
    }
  }

  Widget _buildUserInfo(BuildContext context, dynamic item) {
    if (item == null) {
      return const SizedBox.shrink(); // 返回一个空的占位符
    }

    final String avatar = item['avatar'] ?? 'images/avatar.png';
    final String nickname = item['nickname'].toString();
    final String gender = item['sex:'].toString();
    final String age = item['age'].toString();
    final String level = item['level'].toString();

    return ListTile(
      contentPadding: const EdgeInsets.symmetric(horizontal: 0), // 设置左右内边距
      leading: InkWell(
          onTap: () {
            // 跳转到用户主页
            Get.to(UserDetail(
              userId: item['user_id'].toString(),
            ));
          },
          child: MyAvatarWidget(image: avatar),
      ),
      title: Row(
        children: [
          Text(nickname),
          const SizedBox(width: 5),
          LevelSpan(level: level),
          const SizedBox(width: 5),
          const AuthSpan()
        ],
      ),
      subtitle: Row(
        children: [
          const SizedBox(
            height: 30,
          ),
          AgeSpan(gender: gender, age: age)
        ],
      ),
    );
  }

  Widget _buildRichText(BuildContext context, Map<String, dynamic>? item) {
    if (item == null) {
      return const SizedBox.shrink();
    }
    String content = item['content'];
    return Column(
      children: [
        RichText(
          text: TextSpan(
            text: content,
            style: const TextStyle(fontSize: 15, color: Colors.black87),
          ),
        ),
        const SizedBox(
          height: 15,
        )
      ],
    );
  }
}
